package com.yunxi.service.dubboService.impl.otd;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.yunxi.bizToHub.pojo.EaiLogs;
import com.yunxi.bizToHub.pojo.MonthPlanDataVO;
import com.yunxi.bizToHub.pojo.OtdModelVO;
import com.yunxi.bizToHub.service.EaiLogBizToHubService;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.otd.MonthPlan;
import com.yunxi.model.otd.MonthPlanDetail;
import com.yunxi.model.otd.OtdIfMonthPlan;
import com.yunxi.otd.pojo.MonthPlanDetailVO;
import com.yunxi.otd.pojo.MonthPlanImportDTO;
import com.yunxi.otd.pojo.MonthPlanImportVO;
import com.yunxi.otd.pojo.MonthPlanVO;
import com.yunxi.otd.service.MonthPlanDubboService;
import com.yunxi.rocketMq.producer.OtdMonthPlanProducer;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.otd.MonthPlanDetailService;
import com.yunxi.service.localService.otd.MonthPlanService;
import com.yunxi.service.localService.otd.OtdIfMonthPlanService;
import com.yunxi.service.localService.otd.OtdIfProducePlanService;
import com.yunxi.service.localService.VehicleProductViewService;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 月度需求计划 服务实现类
 * </p>
 *
 * @author XUQI
 * @since 2019-05-06
 */
//@Service(version = "${demo.service.version}",
//    application = "${dubbo.application.id}",
//    protocol = "${dubbo.protocol.id}",
//    registry = "${dubbo.registry.id}"
//)
public class MonthPlanDubboServiceImpl implements MonthPlanDubboService {

    private static final Logger logger = LoggerFactory.getLogger(MonthPlanDubboServiceImpl.class);


    @Autowired
    @Qualifier(value = "monthPlanServiceImpl")
    MonthPlanService monthPlanService;

    @Autowired
    @Qualifier(value = "monthPlanDetailServiceImpl")
    MonthPlanDetailService monthPlanDetailService;

    @Autowired
    @Qualifier("vehicleProductViewServiceImpl")
    VehicleProductViewService productService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService code;

    @Autowired
    @Qualifier(value = "otdIfMonthPlanServiceImpl")
    OtdIfMonthPlanService ifMonthPlanService;

    @Autowired
    @Qualifier("otdIfProducePlanServiceImpl")
    OtdIfProducePlanService producePlanService;

    @Value("${mq.switch}")
    private String mq_switch;

    @Autowired
    private OtdMonthPlanProducer otdMonthPlanProducer;

    @Autowired
    private EaiLogBizToHubService eaiLogBizToHubServiceImpl;

    @Override
    public PageInfo pageByVo(MonthPlanVO monthPlanVO, Integer pageNum, Integer pageSize) {
        return monthPlanService.pageByVo(monthPlanVO, pageNum, pageSize);
    }

    @Override
    public List<MonthPlanDetailVO> findMonthPlanDetailByCode(String monthPlanCode) {
        return monthPlanDetailService.findMonthPlanDetailByCode(monthPlanCode);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult modifyMonthPlanDetail(MonthPlanDetailVO detailVO, LoginInfo info) {
        MonthPlanDetail detail = new MonthPlanDetail();
        BeanUtils.copyProperties(detailVO, detail);
        detail.setUpdateBy(info.getRealName());
        if (!monthPlanDetailService.updateById(detail)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.fail(-1, "数据过期");
        }
        //更新主单数量
        monthPlanService.modifyMonthPlanNum(detailVO.getMonthPlanCode(), info.getRealName());

        return ResponseUtil.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult importMonthPlan(MonthPlanImportDTO importDTO, LoginInfo info) {
        //当前年月
        String year = importDTO.getYear();
        String month = importDTO.getMonth();
        if (month.length() == 1) {
            month = "0" + month;
        }
        // 制作年月是否有其他版本，有则本次新增追加版本号
        Integer planVersion = monthPlanService.findMonthPlanVersionByYearMonth(year, month);
        if (planVersion == null) {
            planVersion = 1;
        } else {
            planVersion++;
        }
        //M1年月
        LocalDate date = LocalDate.now().withYear(Integer.valueOf(year)).withMonth(Integer.valueOf(month))
            .plusMonths(1);

        String m1Year = String.valueOf(date.getYear());
        String m1Month = String.valueOf(date.getMonthValue());
        if (m1Month.length() == 1) {
            m1Month = "0" + m1Month;
        }

        // 月度主表
        MonthPlan monthPlan = new MonthPlan();
        monthPlan.setMonthPlanCode(code.createCode("MP", 4));
        monthPlan.setYear(year);
        monthPlan.setMonth(month);
        monthPlan.setM1YearMonth(m1Year + m1Month);
        monthPlan.setState("1");
        monthPlan.setCreateBy(info.getUserCode());
        monthPlan.setUpdateBy(info.getUserCode());
        monthPlan.setPlanVersion(planVersion);

        // 月度明细
        Integer m1SumNum = 0, m2SumNum = 0, m3SumNum = 0;
        List<MonthPlanDetail> detailList = new ArrayList<>();

        for (MonthPlanImportVO detailVO : importDTO.getDataList()) {
            String productCode = productService
                .findProductCodeBySub(detailVO.getCatalogCode(), detailVO.getColorInCode(), detailVO.getColorOutCode());
            if (StringUtils.isEmpty(productCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseUtil.fail(-1, "产品信息错误");
            }

            // 汇总数量
            m1SumNum += detailVO.getM1Num();
            m2SumNum += detailVO.getM2Num();
            m3SumNum += detailVO.getM3Num();
            // VO to entity
            MonthPlanDetail detail = new MonthPlanDetail();
            BeanUtils.copyProperties(detailVO, detail);
            detail.setMonthPlanCode(monthPlan.getMonthPlanCode());
            detail.setProductCode(productCode);
            detail.setCustomPackCode(detailVO.getCustomPackCode());
            detail.setM1Num(detailVO.getM1Num());
            detail.setM2Num(detailVO.getM2Num());
            detail.setM3Num(detailVO.getM3Num());
            detail.setCreateBy(info.getUserCode());
            detail.setUpdateBy(info.getUserCode());
            detailList.add(detail);
        }

        monthPlan.setM1SumNum(m1SumNum);
        monthPlan.setM2SumNum(m2SumNum);
        monthPlan.setM3SumNum(m3SumNum);
        // 保存
        monthPlanService.save(monthPlan);
        monthPlanDetailService.saveBatch(detailList);

        return ResponseUtil.ok();
    }


    /**
     * 下发月度计划
     *
     * @param monthPlanId 月计划id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult sendMonthPlan(String monthPlanId, LoginInfo info) {
        //月计划数据
        List<com.yunxi.bizToHub.pojo.MonthPlanVO> orders = new ArrayList<>();
        //选装包list
        List<OtdModelVO> packages = new ArrayList<>();
        // 查询月计划
        MonthPlan monthPlan = monthPlanService.getById(monthPlanId);
        // 明细
        List<MonthPlanDetailVO> list = monthPlanDetailService.findMonthPlanDetailByCode(monthPlan.getMonthPlanCode());
        //计算月份
        LocalDate now = LocalDate.of(Integer.valueOf(monthPlan.getYear()), Integer.valueOf(monthPlan.getMonth()), 1);
        LocalDate m1Date = now.plusMonths(1);
        LocalDate m2Date = now.plusMonths(2);
        LocalDate m3Date = now.plusMonths(3);

        //行项目编号
        int itemNo = 10;
        // 配置识别码
        Map<String, String> packageNoMap = new HashMap<>();
        packageNoMap.put("", "10000");
        int initPackageNo = 10000;
        // 新增接口数据
        for (MonthPlanDetailVO detail : list) {
            // 配置识别码
            int packageNo;
            //选装包
            String packageCode = StringUtils.isEmpty(detail.getCustomPackCode()) ? "" : detail.getCustomPackCode();
            //校验是否已添加相同选装包
            if (packageNoMap.get(packageCode) == null) {
                initPackageNo += 100;
                packageNo = initPackageNo;
                packageNoMap.put(packageCode, String.valueOf(packageNo));
                // 选装包配置
                List<OtdModelVO> modelVOS = productService
                    .findConfigByCustomPackCode(detail.getProduct().getCatalogCode(), packageCode,
                        String.valueOf(packageNo));
                packages.addAll(modelVOS);
            } else {
                packageNo = Integer.parseInt(packageNoMap.get(packageCode));
            }

            if (detail.getM1Num() != 0) {
                itemNo = createInterfaceData(detail, detail.getM1Num(), m1Date, itemNo, orders, info, packageNo);
            }
            if (detail.getM2Num() != 0) {
                itemNo = createInterfaceData(detail, detail.getM2Num(), m2Date, itemNo, orders, info, packageNo);
            }
            if (detail.getM3Num() != 0) {
                itemNo = createInterfaceData(detail, detail.getM3Num(), m3Date, itemNo, orders, info, packageNo);
            }
        }

        monthPlan.setState("2");//已下发
        monthPlan.setUpdateBy(info.getRealName());
        monthPlanService.updateById(monthPlan);

        MonthPlanDataVO dataVO = new MonthPlanDataVO();
        dataVO.setOrders(orders);
        dataVO.setPackages(packages);

        String json = JSONObject.toJSONString(dataVO);
        logger.info("月计划接口下发，JSON:\n" + json);
        //   otdMonthPlanProducer.sendMessage(JSONObject.toJSONString(dataVO));
        if (mq_switch.equals("true")) {
            otdMonthPlanProducer.sendMessage(JSONObject.toJSONString(dataVO));
            return ResponseUtil.ok();
        }
        EaiLogs eaiLogs = new EaiLogs();
        eaiLogs.setPmsEaiContent(JSONObject.toJSONString(dataVO));
        eaiLogBizToHubServiceImpl.saveMonthPlanEaiLog(eaiLogs);
        /*Message message = new Message(rocketConfig.getOtdMonthPlanTopic(), "eaiLog",
            (JSONObject.toJSONString(dataVO)).getBytes());
        try {
            SendResult send = planProducer.getProducer().send(message);
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
        }*/
        return ResponseUtil.ok();
    }


    /**
     * 创建接口数据
     *
     * @param detail 月计划明细
     * @param planNum 水岸
     * @param date 年月
     * @param itemNo 行项目编号
     * @param orders 接口订单对象
     * @return 行项目编号
     */
    private int createInterfaceData(MonthPlanDetailVO detail, Integer planNum, LocalDate date, int itemNo,
        List<com.yunxi.bizToHub.pojo.MonthPlanVO> orders, LoginInfo info, int packageNo) {
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        String year = String.valueOf(date.getYear());
        String month = String.valueOf(date.getMonthValue());
        month = month.length() == 1 ? "0" + month : month;
        // 月天数
        int maxDay = date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();

        //余数
        int remainder = 0;
        //每天数量
        int avgNum = 1;

        if (planNum > maxDay) {
            remainder = planNum % maxDay;
            avgNum = planNum / maxDay;
        }
        for (int i = 1; i <= maxDay; i++) {
            // 总数小于天数时退出循环
            if (planNum < i) {
                break;
            }
            int num = avgNum;
            if (i <= remainder) {
                num++;
            }
            //创建接口表数据
            OtdIfMonthPlan ifMonthPlan = new OtdIfMonthPlan();
            ifMonthPlan.setProductCode(detail.getProduct().getProductCode());
            ifMonthPlan.setCarModel(detail.getProduct().getCatalogCode());
            ifMonthPlan.setOrderYear(year);
            ifMonthPlan.setOrderMonth(month);
//            ifMonthPlan.setPlanNo(code.createCode("MPLAN", 5));
            ifMonthPlan.setPlanNo(detail.getMonthPlanCode());

            ifMonthPlan.setStartDate(date.format(formatters));
            ifMonthPlan.setWorks("AP21");
            ifMonthPlan.setItemNo(String.valueOf(itemNo));
            ifMonthPlan.setNum(num);
            ifMonthPlan.setCreateBy(info.getRealName());
            ifMonthPlan.setUpdateBy(info.getRealName());
            ifMonthPlanService.save(ifMonthPlan);

            //创建接口传输对象
            com.yunxi.bizToHub.pojo.MonthPlanVO plan = new com.yunxi.bizToHub.pojo.MonthPlanVO();
            // plan.setPackage_no();
            plan.setCar_model(ifMonthPlan.getCarModel());
            //plan.setCar_model("AM861BFMCHL19B0");
            plan.setItem_no(ifMonthPlan.getItemNo());
            plan.setPlanno(ifMonthPlan.getPlanNo());
            plan.setStart_date(ifMonthPlan.getStartDate());
            plan.setWerks(ifMonthPlan.getWorks());
            plan.setQty(String.valueOf(ifMonthPlan.getNum()));
            plan.setPackage_no(String.valueOf(packageNo));
            orders.add(plan);
            //日期加一
            date = date.plusDays(1);
            itemNo += 10;
        }
        return itemNo;
    }
}
